package com.ugoodtech.mdcc.web.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.VstarCustomerSatisfactionReport.*;
import com.ugoodtech.mdcc.core.domain.VstarServiceReport.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.impl.VstarCustomerServiceImpl;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.service.VstarCustomerSatisfactionReportService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class VstarCustomerSatisfactionReportServiceImpl implements VstarCustomerSatisfactionReportService {

    private static final Logger logger = LoggerFactory.getLogger(VstarCustomerSatisfactionReportServiceImpl.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private ServiceReportRecorderRepository serviceReportRecorderRepository;

    @Autowired
    private NationRepository nationRepository;

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private StationCustomerReportRepository stationCustomerReportRepository;

    @Autowired
    private VstarCustomerServiceImpl vstarCustomerService;

    @Autowired
    private DepartmentRepository departmentRepository;

    private List<String[]> otherCustomerStatList = new ArrayList<>();

    private List<String[]> otherCustomerTypeList = new ArrayList<>();

    private List<String[]> otherPaintBrandList = new ArrayList<>();

    private List<String[]> otherMaintainBigProblem = new ArrayList<>();

    private List<String[]> otherStationAppeal = new ArrayList<>();

    private int countPerson = 0;


    @Override
    public JsonResponse statReport(String provinces, String brand, String category, Long stationId,
                                   Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, Long serviceType,
                                   Integer serviceNum, Long userId, Boolean iFillin, String scoreType, String followType, Long loginUserId, String stationNum, Long departmentId) {
        if (serviceNum != null && serviceNum != 0) {
            if (serviceNum >= Long.MAX_VALUE) {
                return JsonResponse.errorResponseWithError("抱歉", "服务次数太多");
            }
        }
        List<CustomerRegularReport> customerRegularReportList = vstarCustomerService.
                builder(provinces, brand, category, stationId, serviceStartTime, serviceEndTime, startTime, endTime,
                        serviceType, serviceNum, userId, iFillin, scoreType, followType, loginUserId, departmentId);
        List<StationReport> reportList = toStationReport(customerRegularReportList);
        otherCustomerStatList = new ArrayList<>();
        otherCustomerTypeList = new ArrayList<>();
        otherPaintBrandList = new ArrayList<>();
        otherMaintainBigProblem = new ArrayList<>();
        otherStationAppeal = new ArrayList<>();
        countPerson = reportList.size();
        otherPaintBrandList = new ArrayList<>();
        logger.info("查出的满意度报告有：" + countPerson + "份");

        VstarCustomerSatisfactionReport statCustomerReport = new VstarCustomerSatisfactionReport();
        statCustomerReport.setCountPerson(countPerson);
        //设置销售省份
        statCustomerReport.setProvinceList(getProvinceList(reportList));
        //设置客户状态
        statCustomerReport.setCustomerStatList(getCustomerStatList(reportList));
        //其他客户状态
        statCustomerReport.setOthercustomerStatList(otherCustomerStatList);
        //客户类型
        statCustomerReport.setCustomerTypeList(getCustomerTypeList(reportList));
        //其他客户类型
        statCustomerReport.setOtherCustomerTypeList(otherCustomerTypeList);
        //设置油漆品牌
        statCustomerReport.setPaintBrandList(getPaintBrandList(reportList));
        //设置其他油漆品牌
        statCustomerReport.setOtherPaintBrandList(otherPaintBrandList);
        //品牌定位
        statCustomerReport.setProductPositionList(getProductPositionList(reportList));
        //设置服务结果
        statCustomerReport.setReport_results(getResults(reportList));
        //设置维修站类型
        statCustomerReport.setStationTypelist(getStationType(reportList));
        //该维修站目前钣喷维修流程中面对最大问题
        statCustomerReport.setMaintainBigProblem(getMaintainBigProblemList(reportList));
        //该维修站的主要诉求
        statCustomerReport.setStationAppeal(getStationAppeal(reportList));
        //统计服务目标
        statCustomerReport.setVstarServiceReport_target(getTarget(reportList));
        //统计服务结果
        statCustomerReport.setVstarServiceReport_results(getResults(reportList));

        if (StringUtils.isNotEmpty(brand) && StringUtils.isEmpty(category)) {
            Integer IBS = 0;
            Integer BPC = 0;
            Integer FBS = 0;
            Integer DEALERS = 0;
            String[] brandArray = brand.split(",");
            Map<String, Integer> countBrandMap = new HashMap<>();
            List<String[]> brandStr = new ArrayList<>();
            List<String[]> otherBrandArray = new ArrayList<>();
            Map<String, Integer> otherCountBrandMap = new HashMap<>();
            for (StationReport report : reportList) {
                for (String brandName : brandArray) {
                    if (StringUtils.isNotEmpty(brandName)) {
                        if (report.getStation().getCategory().equals(Constants.FOR_S) && report.getStation().getBrand().indexOf(brandName) != -1) {
                            if (countBrandMap.containsKey(brandName)) {
                                Integer value = countBrandMap.get(brandName);
                                countBrandMap.put(brandName, value + 1);
                            } else {
                                countBrandMap.put(brandName, 1);
                            }
                        }
                    }
                }
                if (report.getStation().getCategory().equals(Constants.IBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    IBS += 1;
                }
                if (report.getStation().getCategory().equals(Constants.BPC)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    BPC += 1;
                }
                if (report.getStation().getCategory().equals(Constants.FBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    FBS += 1;
                }
                if (report.getStation().getCategory().equals(Constants.DEALERS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    DEALERS += 1;
                }
            }
            String[] str = new String[2];
            for (Map.Entry<String, Integer> entry : countBrandMap.entrySet()) {
                str = new String[3];
                str[0] = entry.getKey();
                str[1] = entry.getValue().toString();
                str[2] = "";
                brandStr.add(str);
            }
            if (IBS != 0) {
                str = new String[3];
                str[0] = Constants.IBS;
                str[1] = String.valueOf(IBS);
                str[2] = "";
                brandStr.add(str);
            }
            if (BPC != 0) {
                str = new String[3];
                str[0] = Constants.BPC;
                str[1] = String.valueOf(BPC);
                str[2] = "";
                brandStr.add(str);
            }
            if (FBS != 0) {
                str = new String[3];
                str[0] = Constants.FBS;
                str[1] = String.valueOf(FBS);
                str[2] = "";
                brandStr.add(str);
            }
            if (DEALERS != 0) {
                str = new String[3];
                str[0] = Constants.DEALERS;
                str[1] = String.valueOf(DEALERS);
                str[2] = "";
                brandStr.add(str);
            }
            for (Map.Entry<String, Integer> entry : otherCountBrandMap.entrySet()) {
                String[] otherBrand = new String[3];
                otherBrand[0] = entry.getKey();
                otherBrand[1] = entry.getValue().toString();
                otherBrand[2] = "";
                otherBrandArray.add(otherBrand);
            }
            VstarCustomerSatisfactionReport_Brand countBrand = new VstarCustomerSatisfactionReport_Brand();
            countBrand.setBrandArray(brandStr);
            countBrand.setOtherBrandList(otherBrandArray);
            countBrand.setOtherBrand("");
            statCustomerReport.setVstarCustomerSatisfactionReport_brand(countBrand);
        } else {
            if (StringUtils.isNotEmpty(brand)) {
                String[] brandArray = brand.split(",");
                statCustomerReport.setVstarCustomerSatisfactionReport_brand(getBrand_new(brandArray, reportList));
            } else {
                statCustomerReport.setVstarCustomerSatisfactionReport_brand(getBrand_new(null, reportList));
            }
        }
        statCustomerReport.setVstarServiceReport_Target(getTarget(reportList));
        return JsonResponse.successResponseWithData(statCustomerReport);
    }

    //统计维修站类型
    private List<String[]> getStationType(List<StationReport> reports) {
        Long BPC = 0L;
        Long FBS = 0L;
        Long fourS = 0L;
        Long IBS = 0L;
        Long DEALERS = 0L;
        for (StationReport report : reports) {
            if (report.getStation().getCategory().equals(Constants.BPC)) {
                BPC += 1;
            }
            if (report.getStation().getCategory().equals(Constants.FBS)) {
                FBS += 1;
            }
            if (report.getStation().getCategory().equals(Constants.FOR_S)) {
                fourS += 1;
            }
            if (report.getStation().getCategory().equals(Constants.IBS)) {
                IBS += 1;
            }
            if (report.getStation().getCategory().equals(Constants.DEALERS)) {
                DEALERS += 1;
            }
        }
        List<String[]> stationType = new ArrayList<>();
        String[] str = new String[3];
        str[0] = "钣喷中心(BPC)";
        str[1] = BPC.toString();
        str[2] = "";
        stationType.add(str);

        str = new String[3];
        str[0] = "连锁维修站(FBS)";
        str[1] = FBS.toString();
        str[2] = "";
        stationType.add(str);

        str = new String[3];
        str[0] = "4S店(4S)";
        str[1] = fourS.toString();
        str[2] = "";
        stationType.add(str);

        str = new String[3];
        str[0] = "独立维修站(IBS)";
        str[1] = IBS.toString();
        str[2] = "";
        stationType.add(str);

        str = new String[3];
        str[0] = "经销商";
        str[1] = DEALERS.toString();
        str[2] = "";
        stationType.add(str);
        return stationType;
    }

    //销售区域
    private List<String[]> getProvinceList(List<StationReport> reports) {
        Map<String, Integer> provinceMap = new HashMap<>();
        for (StationReport stationReport : reports) {
            if (StringUtils.isNotEmpty(stationReport.getStation().getProvince())) {
                String province = stationReport.getStation().getProvince();
                if (provinceMap.containsKey(province)) {
                    Integer value = provinceMap.get(province);
                    provinceMap.put(province, value + 1);
                } else {
                    provinceMap.put(province, 1);
                }
            }
        }
        return toListStringArray(provinceMap);
    }

    //客户状态
    private List<String[]> getCustomerStatList(List<StationReport> reports) {
        Map<String, Integer> customerStatMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reports) {
            if (report.getStation().getCustomerStat() != null && report.getStation().getCustomerStat() != 0) {
                Long customerStatId = report.getStation().getCustomerStat();
                answerOption = questionAnswerOptionRepository.findOne(customerStatId);
                if (customerStatMap.containsKey(answerOption.getName())) {
                    Integer value = customerStatMap.get(answerOption.getName());
                    customerStatMap.put(answerOption.getName(), value + 1);
                } else {
                    customerStatMap.put(answerOption.getName(), 1);
                }
                if (customerStatId == 362L) {
                    // todo 其他客户状态
                    String answer = getStationColorReport_AnswerOther(report, 184L);
                    if (answer == null) {
                        continue;
                    }
                    if (otherMap.containsKey(answer)) {
                        Integer value = otherMap.get(answer);
                        otherMap.put(answer, value + 1);
                    } else {
                        otherMap.put(answer, 1);
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherCustomerStatList = toListStringArray(otherMap);
        }
        return toListStringArray(customerStatMap);
    }

    //油漆品牌
    private List<String[]> getPaintBrandList(List<StationReport> reports) {
        Map<String, Integer> paintBrandMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reports) {
            if (StringUtils.isNotEmpty(report.getStation().getPaintBrand())) {
                String[] paintBrandids = report.getStation().getPaintBrand().split(",");
                for (String id : paintBrandids) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answerOption!=null && answerOption.getName() != null) {
                        if (paintBrandMap.containsKey(answerOption.getName())) {
                            Integer value = paintBrandMap.get(answerOption.getName());
                            paintBrandMap.put(answerOption.getName(), value + 1);
                        } else {
                            paintBrandMap.put(answerOption.getName(), 1);
                        }
                    }
                    if (id.equals("280")) {
                        //todo 其他的油漆品牌
                        String answer = getStationColorReport_AnswerOther(report, 13L);
                        if (answer == null) {
                            continue;
                        }
                        if (otherMap.containsKey(answer)) {
                            Integer value = otherMap.get(answer);
                            otherMap.put(answer, value + 1);
                        } else {
                            otherMap.put(answer, 1);
                        }
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherPaintBrandList = toListStringArray(otherMap);
        }
        return toListStringArray(paintBrandMap);
    }

    //品牌定位
    private List<String[]> getProductPositionList(List<StationReport> reports) {
        Map<String, Integer> productPositionMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reports) {
            if (StringUtils.isNotEmpty(report.getStation().getProductPosition())) {
                String[] productPositionids = report.getStation().getProductPosition().split(",");
                for (String id : productPositionids) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answerOption!=null && answerOption.getName() != null) {
                        if (productPositionMap.containsKey(answerOption.getName())) {
                            Integer value = productPositionMap.get(answerOption.getName());
                            productPositionMap.put(answerOption.getName(), value + 1);
                        } else {
                            productPositionMap.put(answerOption.getName(), 1);
                        }
                    }
                }
            }
        }
        return toListStringArray(productPositionMap);
    }

    private String getStationColorReport_AnswerOther(StationReport stationReport, Long questionId) {
        if (stationReport.getStation() != null && stationReport.getStation().getId() != null && stationReport.getStation().getId() != 0) {
            Long stationId = stationReport.getStation().getId();
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.station.id.eq(stationId));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            StationReport report = stationReportRepository.findOne(builder);
            if (report == null) {
                return null;
            }
            StationColorReport colorReport = stationColorReportRepository.selectReport(report.getId(), questionId);
            if (colorReport != null && StringUtils.isNotEmpty(colorReport.getAnswerOther())) {
                return colorReport.getAnswerOther();
            }
        }
        return null;
    }

    //将Map转List
    private List<String[]> toListStringArray(Map<String, Integer> map) {
        List<String[]> strList = new ArrayList<>();
        String[] str = new String[3];
        String[] otherStr = null;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getKey().indexOf("其他") != -1) {
                otherStr = new String[3];
                otherStr[0] = entry.getKey();
                otherStr[1] = entry.getValue().toString();
                otherStr[2] = "";
            } else {
                str = new String[3];
                str[0] = entry.getKey();
                str[1] = entry.getValue().toString();
                str[2] = "";
                strList.add(str);
            }
        }
        if (otherStr != null) {
            strList.add(otherStr);
        }
        return strList;
    }

    private VstarCustomerSatisfactionReport_Brand getBrand_new(String[] brandArray, List<StationReport> reportList) {
        List<String> brandNames = new ArrayList<>();
        for (StationReport report : reportList) {
            if (report.getStation().getCategory().equals(Constants.FOR_S)) {
                String[] brandName = report.getStation().getBrand().split(",");
                for (String brand : brandName) {
                    if (brandArray != null) {
                        for (String str : brandArray) {
                            if (!brand.equals(str)) {
                                continue;
                            } else {
                                if (StringUtils.isNotEmpty(brand)) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    } else {
                        if (StringUtils.isNotEmpty(brand)) {
                            brandNames.add(brand);
                        }
                    }
                }
            } else {
                if (report.getStation().getCategory().equals(Constants.IBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.IBS);
                }
                if (report.getStation().getCategory().equals(Constants.BPC)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.BPC);
                }
                if (report.getStation().getCategory().equals(Constants.FBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.FBS);
                }
                if (report.getStation().getCategory().equals(Constants.DEALERS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.DEALERS);
                }
            }
        }
        return countBrand(brandNames);
    }


    private VstarCustomerSatisfactionReport_Brand countBrand(List<String> brandNames) {
        Map<String, Integer> brandMap = new HashMap<>();
        for (String brand : brandNames) {
            if (brandMap.containsKey(brand)) {
                Integer value = brandMap.get(brand);
                brandMap.put(brand, value + 1);
            } else {
                brandMap.put(brand, 1);
            }
        }
        VstarCustomerSatisfactionReport_Brand brand = new VstarCustomerSatisfactionReport_Brand();
        List<String[]> brandList = new ArrayList<>();
        List<String[]> otherBrnadList = new ArrayList<>();
        Map<String, Integer> otherbrandMap = new HashMap<>();
        for (Map.Entry<String, Integer> entry : brandMap.entrySet()) {
            if (entry.getKey().equals(Constants.IBS) || entry.getKey().equals(Constants.FBS) || entry.getKey().equals(Constants.BPC)) {
                continue;
            }
            String[] brandArray = new String[3];
            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(entry.getKey());
            if (answerOption != null) {
                brandArray[0] = entry.getKey();
                brandArray[1] = entry.getValue().toString();
                brandArray[2] = "";
                brandList.add(brandArray);
            } else {
                if (otherbrandMap.containsKey("其他品牌")) {
                    Integer value = otherbrandMap.get("其他品牌");
                    otherbrandMap.put("其他品牌", value + entry.getValue());
                } else {
                    otherbrandMap.put("其他品牌", entry.getValue());
                }
                String[] otherBrandArray = new String[3];
                otherBrandArray[0] = entry.getKey();
                otherBrandArray[1] = entry.getValue() + "";
                otherBrandArray[2] = "";
                otherBrnadList.add(otherBrandArray);
            }
        }
        for (Map.Entry<String, Integer> entry : brandMap.entrySet()) {
            if (entry.getKey().equals(Constants.IBS) || entry.getKey().equals(Constants.FBS) || entry.getKey().equals(Constants.BPC)) {
                String[] brandArray = new String[3];
                brandArray[0] = entry.getKey();
                brandArray[1] = entry.getValue().toString();
                brandArray[2] = "";
                brandList.add(brandArray);
            }
        }
        if (otherbrandMap != null && !otherbrandMap.isEmpty()) {
            String[] otherBrand = new String[3];
            otherBrand[0] = "其他品牌";
            otherBrand[1] = otherbrandMap.get("其他品牌").toString();
            otherBrand[2] = "";
            brandList.add(otherBrand);
        }
        if (otherBrnadList == null || otherBrnadList.size() <= 0) {
            brand.setOtherBrandList(otherBrnadList);
        }
        brand.setOtherBrandList(otherBrnadList);
        brand.setBrandArray(brandList);
        brand.setCountPerson(countPerson);
        return brand;
    }

    //统计服务目标
    private VstarServiceReport_Target getTarget(List<StationReport> reports) {
        List<String> targetIdList = new ArrayList<>();
        List<StationReport> reportList = new ArrayList<>();
        for (StationReport report : reports) {
            String[] targetIds = report.getServiceTypAnswerIds().split(",");
            for (String target : targetIds) {
                if (StringUtils.isNotEmpty(target)) {
                    targetIdList.add(target);
                    if (target.equals("191")) {
                        reportList.add(report);
                    }
                }
            }
        }
        VstarServiceReport_Target targetList = countTarget(targetIdList);
        targetList.setOtherTarget(targetOther(reportList));
        targetList.setCountPerson(countPerson);
        return targetList;
    }

    private VstarServiceReport_Target countTarget(List<String> targetIdList) {
        Map<Long, Integer> targetMap = new HashMap<>();
        for (String target : targetIdList) {
            if (targetMap.containsKey(Long.valueOf(target))) {
                Integer value = targetMap.get(Long.valueOf(target));
                targetMap.put(Long.valueOf(target), value + 1);
            } else {
                targetMap.put(Long.valueOf(target), 1);
            }
        }
        VstarServiceReport_Target target = new VstarServiceReport_Target();
        List<String[]> targetList = new ArrayList<>();
        for (Map.Entry<Long, Integer> entry : targetMap.entrySet()) {
            String[] targetArray = new String[3];
            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(entry.getKey());
            if (answerOption != null) {
                targetArray[0] = answerOption.getName();
                targetArray[1] = entry.getValue().toString();
                targetArray[2] = "";
                targetList.add(targetArray);
            }
        }
        target.setTarget(targetList);
        target.setCountPerson(countPerson);
        return target;
    }

    private List<String[]> targetOther(List<StationReport> reportList) {
        List<String[]> otherTargerList = new ArrayList<>();
        for (StationReport report : reportList) {
//            if (report.getServiceTypAnswerIds().indexOf("191") == -1) {
//                continue;
//            }
            StationRegularServiceReport serviceReport = stationRegularServiceReportRepository.selectAnswer(report.getId(), 191L);
            if (serviceReport == null) {
                continue;
            }
            String realName = "";
            if (report.getUser() != null) {
                UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
                if (userProfile != null) {
                    if (StringUtils.isNotEmpty(userProfile.getRealName())) {
                        realName = userProfile.getRealName();
                    }
                }
            }
            String[] otherTarger = new String[6];
            otherTarger[0] = report.getStation().getName();
            otherTarger[1] = report.getStation().getStationNum();
            otherTarger[2] = report.getCreationTimeStr();
            otherTarger[3] = serviceReport.getAnswerOther();
            otherTarger[4] = realName;
            otherTarger[5] = "";
            otherTargerList.add(otherTarger);
        }
        return otherTargerList;
    }

    //统计服务结果
    private VstarServiceReport_Results getResults(List<StationReport> reports) {
        VstarServiceReport_Results results = new VstarServiceReport_Results();
        Long noComplete_UnableToFollowUp = 0L;
        Long noComplete_NeedToFollowUp = 0L;
        Long complete = 0L;
        Long complete_NeedOthersToFollowUp = 0L;
        for (StationReport report : reports) {
            noComplete_UnableToFollowUp += (Long) stationRegularServiceReportRepository.count(179L, report.getId());
            noComplete_NeedToFollowUp += (Long) stationRegularServiceReportRepository.count(180L, report.getId());
            complete += (Long) stationRegularServiceReportRepository.count(181L, report.getId());
            complete_NeedOthersToFollowUp += (Long) stationRegularServiceReportRepository.count(182L, report.getId());
        }
        List<VstarServiceReport_CompleteFollowUp> completeFollowUps = new ArrayList<>();
        List<VstarServiceReport_UnFinshedNoFollowUp> unFinshedNoFollowUps = new ArrayList<>();
        List<VstarServiceReport_UnFinshedFollowUp> unFinshedFollowUps = new ArrayList<>();

        List<String[]> noComplete_UnFollowUp = new ArrayList<>();
        List<String[]> noComplete_needFollowUp = new ArrayList<>();
        List<String[]> completeReport = new ArrayList<>();
        List<String[]> complete_needFollowUp = new ArrayList<>();
        List<String[]> manageProduct = new ArrayList<>();
        List<String[]> planReport = new ArrayList<>();

        for (StationReport report : reports) {
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            QStationRegularServiceReport regularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(regularServiceReport.deleted.eq(false));
            builder.and(regularServiceReport.stationReport.id.eq(report.getId()));
            builder.and(regularServiceReport.questionId.eq(156L));
//            builder.and(regularServiceReport.answerId.ne("181"));
            StationRegularServiceReport serviceReport = stationRegularServiceReportRepository.findOne(builder);
            if (serviceReport != null) {
                if (Long.valueOf(serviceReport.getAnswerId()) == 179L) {
                    String[] str = getStrArray(report, userProfile);
                    noComplete_UnFollowUp.add(str);

                    VstarServiceReport_CompleteFollowUp completeFollowUp = new VstarServiceReport_CompleteFollowUp();
                    completeFollowUp.setStationName(report.getStation().getName());
                    completeFollowUp.setStationNum(report.getStation().getStationNum());
                    completeFollowUp.setCreateTime(report.getCreationTimeStr());
                    completeFollowUp.setId(report.getId());
                    completeFollowUp.setUserName(userProfile.getRealName());
                    completeFollowUp.setAnswer(serviceReport.getAnswerOther());
                    completeFollowUps.add(completeFollowUp);
                }
                if (Long.valueOf(serviceReport.getAnswerId()) == 180L) {
                    String[] str = getStrArray(report, userProfile);
                    noComplete_needFollowUp.add(str);

                    VstarServiceReport_UnFinshedNoFollowUp unFinshedNoFollowUp = new VstarServiceReport_UnFinshedNoFollowUp();
                    unFinshedNoFollowUp.setStationName(report.getStation().getName());
                    unFinshedNoFollowUp.setStationNum(report.getStation().getStationNum());
                    unFinshedNoFollowUp.setCreateTime(report.getCreationTimeStr());
                    unFinshedNoFollowUp.setId(report.getId());
                    unFinshedNoFollowUp.setUserName(userProfile.getRealName());
                    unFinshedNoFollowUp.setAnswer(serviceReport.getAnswerOther());
                    unFinshedNoFollowUps.add(unFinshedNoFollowUp);
                }

                //已完成
                if (Long.valueOf(serviceReport.getAnswerId()).equals(181L)) {
                    String[] str = getStrArray(report, userProfile);
                    completeReport.add(str);
                }

                if (Long.valueOf(serviceReport.getAnswerId()) == 182L) {
                    String[] str = getStrArray(report, userProfile);
                    complete_needFollowUp.add(str);

                    VstarServiceReport_UnFinshedFollowUp unFinshedFollowUp = new VstarServiceReport_UnFinshedFollowUp();
                    unFinshedFollowUp.setStationName(report.getStation().getName());
                    unFinshedFollowUp.setStationNum(report.getStation().getStationNum());
                    unFinshedFollowUp.setCreateTime(report.getCreationTimeStr());
                    unFinshedFollowUp.setId(report.getId());
                    if (userProfile != null) {
                        unFinshedFollowUp.setUserName(userProfile.getRealName());
                    } else {
                        unFinshedFollowUp.setUserName("");
                    }
                    if (StringUtils.isNotEmpty(report.getDeparmentIds())) {
                        String[] departmentIds = report.getDeparmentIds().split(",");
                        StringBuffer stringBuffer = new StringBuffer("");
                        for (String id : departmentIds) {
                            if (StringUtils.isNotEmpty(id)) {
                                Department department = departmentRepository.findOne(Long.valueOf(id));
                                if (department != null && StringUtils.isNotEmpty(department.getName())) {
                                    stringBuffer.append(department.getName() + ",");
                                }
                            }
                        }
                        unFinshedFollowUp.setAnswer(stringBuffer.toString());
                    }
                    unFinshedFollowUps.add(unFinshedFollowUp);
                }

                //处理产品问题（投诉）
                if (Long.valueOf(serviceReport.getAnswerId()).equals(246L)) {
                    String[] str = getStrArray(report, userProfile);
                    manageProduct.add(str);
                }
                //计划进行该项工作，尚未开展
                if (Long.valueOf(serviceReport.getAnswerId()).equals(354L)) {
                    String[] str = getStrArray(report, userProfile);
                    planReport.add(str);
                }

            }
        }

        results.setManageProduct(manageProduct);
        results.setNoComplete_UnFollowUp(noComplete_UnFollowUp);
        results.setNoComplete_needFollowUp(noComplete_needFollowUp);
        results.setCompleteReport(completeReport);
        results.setComplete_needFollowUp(complete_needFollowUp);
        results.setPlanReport(planReport);

        results.setCompleteFollowUps(completeFollowUps);
        results.setUnFinshedNoFollowUps(unFinshedNoFollowUps);
        results.setUnFinshedFollowUps(unFinshedFollowUps);
        results.setNoComplete_UnableToFollowUp(noComplete_UnableToFollowUp.intValue());
        results.setNoComplete_NeedToFollowUp(noComplete_NeedToFollowUp.intValue());
        results.setComplete(complete.intValue());
        results.setComplete_NeedOthersToFollowUp(complete_NeedOthersToFollowUp.intValue());
        results.setCountPerson(noComplete_UnableToFollowUp.intValue() + noComplete_NeedToFollowUp.intValue() + complete.intValue() + complete_NeedOthersToFollowUp.intValue());
        return results;
    }

    //客户类型
    private List<String[]> getCustomerTypeList(List<StationReport> reports) {
        Map<String, Integer> customerTypeMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reports) {
            if (report.getStation().getCustomerType() != null && report.getStation().getCustomerType() != 0) {
                Long customerTypeId = report.getStation().getCustomerType();
                answerOption = questionAnswerOptionRepository.findOne(customerTypeId);
                if (customerTypeMap.containsKey(answerOption.getName())) {
                    Integer value = customerTypeMap.get(answerOption.getName());
                    customerTypeMap.put(answerOption.getName(), value + 1);
                } else {
                    customerTypeMap.put(answerOption.getName(), 1);
                }
                if (customerTypeId == 366L) {
                    // todo 其他客户类型
                    String answer = getStationColorReport_AnswerOther(report, 185L);
                    if (answer == null) {
                        continue;
                    }
                    if (otherMap.containsKey(answer)) {
                        Integer value = otherMap.get(answer);
                        otherMap.put(answer, value + 1);
                    } else {
                        otherMap.put(answer, 1);
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherCustomerTypeList = toListStringArray(otherMap);
        }
        return toListStringArray(customerTypeMap);
    }

    //维修站目前钣喷维修流程中面对最大问题
    private List<String[]> getMaintainBigProblemList(List<StationReport> reports) {
        Map<String, Integer> maintainBigProblemMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        StationColorReport stationColorReport = null;
        for (StationReport report : reports) {
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            builder.and(qStationReport.auditing.eq(Constants.AUDIT_TRUE));
            builder.and(qStationReport.station.id.eq(report.getStation().getId()));
            StationReport stationReport = stationReportRepository.findOne(builder);
            if (stationReport == null) {
                logger.info("ID为：" + report.getStation().getId() + "的维修站没有基础报告");
                continue;
            }
            stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 56L);
            if (stationColorReport != null && StringUtils.isNotEmpty(stationColorReport.getAnswerId())) {
                String[] problemIds = stationColorReport.getAnswerId().split(",");
                for (String id : problemIds) {
                    if (StringUtils.isNotEmpty(id)) {
                        answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(Long.valueOf(id)));
                        if (maintainBigProblemMap.containsKey(answerOption.getName())) {
                            Integer value = maintainBigProblemMap.get(answerOption.getName());
                            maintainBigProblemMap.put(answerOption.getName(), value + 1);
                        } else {
                            maintainBigProblemMap.put(answerOption.getName(), 1);
                        }
                        if (id.equals("266")) {
                            // todo 其他面对最大问题
                            String answer = getStationColorReport_AnswerOther(stationReport, 56L);
                            if (answer == null) {
                                continue;
                            }
                            if (otherMap.containsKey(answer)) {
                                Integer value = otherMap.get(answer);
                                otherMap.put(answer, value + 1);
                            } else {
                                otherMap.put(answer, 1);
                            }
                        }
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherMaintainBigProblem = toListStringArray(otherMap);
        }
        return toListStringArray(maintainBigProblemMap);
    }

    //维修站的主要诉求
    private List<String[]> getStationAppeal(List<StationReport> reports) {
        Map<String, Integer> stationAppealMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        StationColorReport stationColorReport = null;
        for (StationReport report : reports) {
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            builder.and(qStationReport.auditing.eq(Constants.AUDIT_TRUE));
            builder.and(qStationReport.station.id.eq(report.getStation().getId()));
            StationReport stationReport = stationReportRepository.findOne(builder);
            if (stationReport == null) {
                logger.info("ID为：" + report.getStation().getId() + "的维修站没有基础报告");
                continue;
            }
            stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 59L);
            if (stationColorReport != null && StringUtils.isNotEmpty(stationColorReport.getAnswerId())) {
                String[] appealIds = stationColorReport.getAnswerId().split(",");
                for (String id : appealIds) {
                    if (StringUtils.isNotEmpty(id)) {
                        answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(Long.valueOf(id)));
                        if (stationAppealMap.containsKey(answerOption.getName())) {
                            Integer value = stationAppealMap.get(answerOption.getName());
                            stationAppealMap.put(answerOption.getName(), value + 1);
                        } else {
                            stationAppealMap.put(answerOption.getName(), 1);
                        }
                        if (id.equals("272")) {
                            // todo 其他主要诉求
                            String answer = getStationColorReport_AnswerOther(stationReport, 59L);
                            if (answer == null) {
                                continue;
                            }
                            if (otherMap.containsKey(answer)) {
                                Integer value = otherMap.get(answer);
                                otherMap.put(answer, value + 1);
                            } else {
                                otherMap.put(answer, 1);
                            }
                        }
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherStationAppeal = toListStringArray(otherMap);
        }
        return toListStringArray(stationAppealMap);
    }


    //筛选条件
    private List<CustomerRegularReport> builder(String provinces, String brand, String category, Long stationId,
                                                Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, Long serviceType,
                                                Integer serviceNum, Long userId, Boolean iFillin, String scoreType, String followType, Long loginUserId, String stationNum) {
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.customerReport.isNotNull());
        /**
         * 判断是否是经销商
         * 经销商：拿出经销商绑定的维修站ID 进行筛选
         * 内部人员：拿出绑定的省份 进行筛选
         */
        User user = userRepository.findOne(loginUserId);
        UserProfile userProfile = userProfileRepository.findByUserId(loginUserId);
        if (userProfile == null) {
            return null;
        }
        if (StringUtils.isNotEmpty(provinces)) {
            String[] province = provinces.split(",");
            builder.and(qCustomerRegularReport.regularReport.station.province.in(province));
        } else if (user.getUserType().equals(UserType.dealers)) {
            List<Station> stationList = userProfile.getStationList();
            Long[] stationIds = new Long[stationList.size()];
            for (int i = 0; i < stationList.size(); i++) {
                stationIds[i] = stationList.get(i).getId();
            }
            builder.and(qCustomerRegularReport.regularReport.station.id.in(stationIds));
        } else {
            List<Nation> nationList = userProfile.getNationList();
            String[] provinceArray = new String[nationList.size()];
            for (int i = 0; i < nationList.size(); i++) {
                provinceArray[i] = nationList.get(i).getProvince();
            }
            builder.and(qCustomerRegularReport.regularReport.station.province.in(provinceArray));
        }

        if (StringUtils.isNotEmpty(brand)) {
            String[] brandArray = brand.split(",");
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (int i = 0; i < brandArray.length; i++) {
                orBuilder.or(qCustomerRegularReport.regularReport.station.brand.like("%" + brandArray[i] + "%"));
            }
            builder.and(orBuilder);
        } else {
            List<Brand> brandList = userProfile.getBrandList();
            if (brandList != null && brandList.size() > 0) {
                BooleanBuilder orBuilder = new BooleanBuilder();
                for (int i = 0; i < brandList.size(); i++) {
                    orBuilder.or(qCustomerRegularReport.regularReport.station.brand.like("%" + brandList.get(i).getBrandName() + "%"));
                }
                builder.and(orBuilder);
            }
        }
        if (StringUtils.isNotEmpty(stationNum)) {
            builder.and(qCustomerRegularReport.regularReport.station.stationNum.like("%" + stationNum + "%"));
        }
        if (StringUtils.isNotEmpty(category)) {
            builder.and(qCustomerRegularReport.regularReport.station.category.eq(category));
        }
        if (stationId != null && stationId != 0) {
            builder.and(qCustomerRegularReport.regularReport.station.id.eq(stationId));
        }
        if (serviceStartTime != null && serviceStartTime != 0 && serviceEndTime != null && serviceEndTime != 0) {
            builder.and(qCustomerRegularReport.regularReport.startServiceTime.after(new Date(serviceStartTime)));
            builder.and(qCustomerRegularReport.regularReport.endServiceTime.before(new Date(serviceEndTime)));
        }
        if (startTime != null && startTime != 0 && endTime != null && endTime != 0) {
            builder.and(qCustomerRegularReport.regularReport.creationTime.after(new Date(startTime)));
            builder.and(qCustomerRegularReport.regularReport.creationTime.before(new Date(endTime)));
        }
        if (serviceType != null && serviceType != 0) {
            builder.and(qCustomerRegularReport.regularReport.serviceTypAnswerIds.like("%" + serviceType + "%"));
        }
        if (serviceNum != null && serviceNum != 0) {
            builder.and(qCustomerRegularReport.regularReport.user.serviceNum.eq(serviceNum));
        }
        if (iFillin != null) {
            if (iFillin.equals(false)) {
                builder.and(qCustomerRegularReport.type.eq(false));
            } else {
                builder.and(qCustomerRegularReport.type.eq(true));
            }
        }
        String[] str = new String[61];
        for (int i = 1; i < str.length; i++) {
            str[i] = i + "";
        }
        String[] notStr = new String[39];
        int index = 61;
        for (int i = 0; i < 39; i++) {
            str[i] = index++ + "";
        }
        if (StringUtils.isNotEmpty(scoreType)) {
            if (scoreType.equals(Constants.FULL_MARKS)) {
                builder.and(qCustomerRegularReport.score.eq("100"));
            }
            if (scoreType.equals(Constants.MORE_THAN_SIXTY)) {
                builder.and(qCustomerRegularReport.score.in(str));
            }
        }

        if (startTime != null && startTime != 0 && endTime != null && endTime != 0) {
            builder.and(qCustomerRegularReport.regularReport.creationTime.after(new Date(startTime)));
            builder.and(qCustomerRegularReport.regularReport.creationTime.before(new Date(endTime)));
        }

        if (userId != null && userId != 0) {
            builder.and(qCustomerRegularReport.regularReport.user.id.eq(userId));
        }

        List<CustomerRegularReport> customerRegularReportList = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builder);
        logger.info("初步查出的报告有：" + customerRegularReportList.size() + "份");
        List<CustomerRegularReport> reportList = new ArrayList<>();
        for (CustomerRegularReport report : customerRegularReportList) {
            if (StringUtils.isNotEmpty(scoreType) && scoreType.equals(Constants.BELOW_THAN_SIXTY)) {
                QStationCustomerReport qStationCustomerReport = QStationCustomerReport.stationCustomerReport;
                builder = new BooleanBuilder();
                builder.and(qStationCustomerReport.deleted.eq(false));
                builder.and(qStationCustomerReport.enabled.eq(true));
                builder.and(qStationCustomerReport.stationReport.id.eq(report.getCustomerReport().getId()));
                List<StationCustomerReport> customerReportList = (List<StationCustomerReport>) stationCustomerReportRepository.findAll();
                for (StationCustomerReport r : customerReportList) {
                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(r.getAnswerId()));
                    if (answerOption.getName().equals("80%") || answerOption.getName().equals("100%")) {
                        continue;
                    }
                }
            }
            reportList.add(report);
        }

        return reportList;
    }

    /**
     * 封裝成StationReport
     *
     * @param customerRegularReportList
     * @return
     */
    private List<StationReport> toStationReport(List<CustomerRegularReport> customerRegularReportList) {
        List<StationReport> stationReports = new ArrayList<>();
        for (CustomerRegularReport report : customerRegularReportList) {
            if (report.getCustomerReport() != null) {
                stationReports.add(report.getRegularReport());
            }
        }
        return stationReports;
    }

    @Override
    public JsonResponse getScore(String provinces, String brand, String category, Long stationId,
                                 Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, Long serviceType,
                                 Integer serviceNum, Long userId, Boolean iFillin, String scoreType, String followType, Long loginUserId, String stationNum, Long departmentId) {
        List<CustomerRegularReport> reportList = builder(provinces, brand, category, stationId, serviceStartTime, serviceEndTime, startTime, endTime, serviceType,
                serviceNum, userId, iFillin, scoreType, followType, loginUserId, stationNum);
        List<String[]> scoreList = getScore(reportList);
        return JsonResponse.successResponseWithData(scoreList);
    }

    private String[] questionId_159 = new String[12];

    private String[] questionId_160 = new String[12];

    private String[] questionId_161 = new String[12];

    private String[] questionId_162 = new String[12];

    private String[] questionId_163 = new String[12];

    private String[] questionId_164 = new String[12];

    private String[] questionId_166 = new String[12];

    //[0~12] [题目名称:0,100分:1,百分比:2,80分:3,百分比:4,60分:5,百分比:6,40分:7,百分比:8,20分:9,百分比:10,平均分:11]
    private String[] initValue(String[] arrayStr) {
        for (int i = 0; i < arrayStr.length; i++) {
            arrayStr[i] = "0";
        }
        return arrayStr;
    }

    private List<String[]> getScore(List<CustomerRegularReport> customerRegularReportList) {
        questionId_159 = initValue(questionId_159);
        questionId_160 = initValue(questionId_160);
        questionId_161 = initValue(questionId_161);
        questionId_162 = initValue(questionId_162);
        questionId_163 = initValue(questionId_163);
        questionId_164 = initValue(questionId_164);
        questionId_166 = initValue(questionId_166);

        questionId_159[0] = "提供这次服务前, 技术服务人员与您的沟通如何？";
        questionId_160[0] = "技术服务人员是否准时抵达现场？";
        questionId_161[0] = "对服务人员形象满意度？(如是否穿上公司制服)";
        questionId_162[0] = "您对这次技术服务人员的工作态度满意度如何？";
        questionId_163[0] = "这次技术服务支持是否达到您的期望？";
        questionId_164[0] = "您对这次技术服务工作整体满意度评分如何？";
        questionId_166[0] = "您对AkzoNobel技术服务工作整体满意度评分如何？";


        List<String[]> scoreList = new ArrayList<>();
        List<StationReport> stationReportList = new ArrayList<>();
        for (CustomerRegularReport customerRegularReport : customerRegularReportList) {
            if (customerRegularReport.getCustomerReport() != null) {
                stationReportList.add(customerRegularReport.getCustomerReport());
            }
        }
        for (StationReport stationReport : stationReportList) {
            BooleanBuilder builder = new BooleanBuilder();
            QStationCustomerReport qStationCustomerReport = QStationCustomerReport.stationCustomerReport;
            builder.and(qStationCustomerReport.deleted.eq(false));
            builder.and(qStationCustomerReport.enabled.eq(true));
            builder.and(qStationCustomerReport.stationReport.id.eq(stationReport.getId()));
            List<StationCustomerReport> stationCustomerReports = (List<StationCustomerReport>) stationCustomerReportRepository.findAll(builder);
            for (StationCustomerReport customerReport : stationCustomerReports) {
                //[0~12] [题目名称:0,100分:1,百分比:2,80分:3,百分比:4,60分:5,百分比:6,40分:7,百分比:8,20分:9,百分比:10,平均分:11]
                //提供这次服务前, 技术服务人员与您的沟通如何？
                if (customerReport.getQuestionId().equals(159L)) {
                    //20分
                    if (customerReport.getAnswerId().equals("192")) {
                        Integer value = Integer.valueOf(questionId_159[9]);
                        questionId_159[9] = String.valueOf(value + 1);
                    }
                    //40分
                    if (customerReport.getAnswerId().equals("198")) {
                        Integer value = Integer.valueOf(questionId_159[7]);
                        questionId_159[7] = String.valueOf(value + 1);
                    }
                    //60分
                    if (customerReport.getAnswerId().equals("204")) {
                        Integer value = Integer.valueOf(questionId_159[5]);
                        questionId_159[5] = String.valueOf(value + 1);
                    }
                    //80分
                    if (customerReport.getAnswerId().equals("210")) {
                        Integer value = Integer.valueOf(questionId_159[3]);
                        questionId_159[3] = String.valueOf(value + 1);
                    }
                    //100分
                    if (customerReport.getAnswerId().equals("216")) {
                        Integer value = Integer.valueOf(questionId_159[1]);
                        questionId_159[1] = String.valueOf(value + 1);
                    }
                }
                //技术服务人员是否准时抵达现场？
                if (customerReport.getQuestionId().equals(160L)) {
                    //20分
                    if (customerReport.getAnswerId().equals("193")) {
                        Integer value = Integer.valueOf(questionId_160[9]);
                        questionId_160[9] = String.valueOf(value + 1);
                    }
                    //40分
                    if (customerReport.getAnswerId().equals("199")) {
                        Integer value = Integer.valueOf(questionId_160[7]);
                        questionId_160[7] = String.valueOf(value + 1);
                    }
                    //60分
                    if (customerReport.getAnswerId().equals("205")) {
                        Integer value = Integer.valueOf(questionId_160[5]);
                        questionId_160[5] = String.valueOf(value + 1);
                    }
                    //80分
                    if (customerReport.getAnswerId().equals("211")) {
                        Integer value = Integer.valueOf(questionId_160[3]);
                        questionId_160[3] = String.valueOf(value + 1);
                    }
                    //100分
                    if (customerReport.getAnswerId().equals("217")) {
                        Integer value = Integer.valueOf(questionId_160[1]);
                        questionId_160[1] = String.valueOf(value + 1);
                    }
                }
                //对服务人员形象满意度？(如是否穿上公司制服)？
                if (customerReport.getQuestionId().equals(161L)) {
                    //20分
                    if (customerReport.getAnswerId().equals("194")) {
                        Integer value = Integer.valueOf(questionId_161[9]);
                        questionId_161[9] = String.valueOf(value + 1);
                    }
                    //40分
                    if (customerReport.getAnswerId().equals("200")) {
                        Integer value = Integer.valueOf(questionId_161[7]);
                        questionId_161[7] = String.valueOf(value + 1);
                    }
                    //60分
                    if (customerReport.getAnswerId().equals("206")) {
                        Integer value = Integer.valueOf(questionId_161[5]);
                        questionId_161[5] = String.valueOf(value + 1);
                    }
                    //80分
                    if (customerReport.getAnswerId().equals("212")) {
                        Integer value = Integer.valueOf(questionId_161[3]);
                        questionId_161[3] = String.valueOf(value + 1);
                    }
                    //100分
                    if (customerReport.getAnswerId().equals("218")) {
                        Integer value = Integer.valueOf(questionId_161[1]);
                        questionId_161[1] = String.valueOf(value + 1);
                    }
                }
                //您对这次技术服务人员的工作态度满意度如何？
                if (customerReport.getQuestionId().equals(162L)) {
                    //20分
                    if (customerReport.getAnswerId().equals("195")) {
                        Integer value = Integer.valueOf(questionId_162[9]);
                        questionId_162[9] = String.valueOf(value + 1);
                    }
                    //40分
                    if (customerReport.getAnswerId().equals("201")) {
                        Integer value = Integer.valueOf(questionId_162[7]);
                        questionId_162[7] = String.valueOf(value + 1);
                    }
                    //60分
                    if (customerReport.getAnswerId().equals("207")) {
                        Integer value = Integer.valueOf(questionId_162[5]);
                        questionId_162[5] = String.valueOf(value + 1);
                    }
                    //80分
                    if (customerReport.getAnswerId().equals("213")) {
                        Integer value = Integer.valueOf(questionId_162[3]);
                        questionId_162[3] = String.valueOf(value + 1);
                    }
                    //100分
                    if (customerReport.getAnswerId().equals("219")) {
                        Integer value = Integer.valueOf(questionId_162[1]);
                        questionId_162[1] = String.valueOf(value + 1);
                    }
                }
                //这次技术服务支持是否达到您的期望？
                if (customerReport.getQuestionId().equals(163L)) {
                    //20分
                    if (customerReport.getAnswerId().equals("196")) {
                        Integer value = Integer.valueOf(questionId_163[9]);
                        questionId_163[9] = String.valueOf(value + 1);
                    }
                    //40分
                    if (customerReport.getAnswerId().equals("202")) {
                        Integer value = Integer.valueOf(questionId_163[7]);
                        questionId_163[7] = String.valueOf(value + 1);
                    }
                    //60分
                    if (customerReport.getAnswerId().equals("208")) {
                        Integer value = Integer.valueOf(questionId_163[5]);
                        questionId_163[5] = String.valueOf(value + 1);
                    }
                    //80分
                    if (customerReport.getAnswerId().equals("214")) {
                        Integer value = Integer.valueOf(questionId_163[3]);
                        questionId_163[3] = String.valueOf(value + 1);
                    }
                    //100分
                    if (customerReport.getAnswerId().equals("220")) {
                        Integer value = Integer.valueOf(questionId_163[1]);
                        questionId_163[1] = String.valueOf(value + 1);
                    }
                }
                //您对这次技术服务工作整体满意度评分如何？
                if (customerReport.getQuestionId().equals(164L)) {
                    //20分
                    if (customerReport.getAnswerId().equals("197")) {
                        Integer value = Integer.valueOf(questionId_164[9]);
                        questionId_164[9] = String.valueOf(value + 1);
                    }
                    //40分
                    if (customerReport.getAnswerId().equals("203")) {
                        Integer value = Integer.valueOf(questionId_164[7]);
                        questionId_164[7] = String.valueOf(value + 1);
                    }
                    //60分
                    if (customerReport.getAnswerId().equals("209")) {
                        Integer value = Integer.valueOf(questionId_164[5]);
                        questionId_164[5] = String.valueOf(value + 1);
                    }
                    //80分
                    if (customerReport.getAnswerId().equals("215")) {
                        Integer value = Integer.valueOf(questionId_164[3]);
                        questionId_164[3] = String.valueOf(value + 1);
                    }
                    //100分
                    if (customerReport.getAnswerId().equals("221")) {
                        Integer value = Integer.valueOf(questionId_164[1]);
                        questionId_164[1] = String.valueOf(value + 1);
                    }
                }
                //您对技术服务人员提供的解决方案感到满意吗?
                if (customerReport.getQuestionId().equals(166L)) {
                    //20分
                    if (customerReport.getAnswerId().equals("241")) {
                        Integer value = Integer.valueOf(questionId_166[9]);
                        questionId_166[9] = String.valueOf(value + 1);
                    }
                    //40分
                    if (customerReport.getAnswerId().equals("242")) {
                        Integer value = Integer.valueOf(questionId_166[7]);
                        questionId_166[7] = String.valueOf(value + 1);
                    }
                    //60分
                    if (customerReport.getAnswerId().equals("243")) {
                        Integer value = Integer.valueOf(questionId_166[5]);
                        questionId_166[5] = String.valueOf(value + 1);
                    }
                    //80分
                    if (customerReport.getAnswerId().equals("244")) {
                        Integer value = Integer.valueOf(questionId_166[3]);
                        questionId_166[3] = String.valueOf(value + 1);
                    }
                    //100分
                    if (customerReport.getAnswerId().equals("245")) {
                        Integer value = Integer.valueOf(questionId_166[1]);
                        questionId_166[1] = String.valueOf(value + 1);
                    }
                }
            }
        }
        //百分比赋值
        questionId_159 = countPercent(questionId_159);
        questionId_160 = countPercent(questionId_160);
        questionId_161 = countPercent(questionId_161);
        questionId_162 = countPercent(questionId_162);
        questionId_163 = countPercent(questionId_163);
        questionId_164 = countPercent(questionId_164);
        questionId_166 = countPercent(questionId_166);
        //平均值赋值
        questionId_159 = countAverage(questionId_159);
        questionId_160 = countAverage(questionId_160);
        questionId_161 = countAverage(questionId_161);
        questionId_162 = countAverage(questionId_162);
        questionId_163 = countAverage(questionId_163);
        questionId_164 = countAverage(questionId_164);
        questionId_166 = countAverage(questionId_166);

        scoreList.add(questionId_159);
        scoreList.add(questionId_160);
        scoreList.add(questionId_161);
        scoreList.add(questionId_162);
        scoreList.add(questionId_163);
        scoreList.add(questionId_164);
        scoreList.add(questionId_166);
        return scoreList;
    }

    //计算百分比
    //[0~12] [题目名称:0,100分:1,百分比:2,80分:3,百分比:4,60分:5,百分比:6,40分:7,百分比:8,20分:9,百分比:10,平均分:11]
    private String[] countPercent(String[] arrayStr) {
        double index1 = Double.valueOf(arrayStr[1]);
        double index3 = Double.valueOf(arrayStr[3]);
        double index5 = Double.valueOf(arrayStr[5]);
        double index7 = Double.valueOf(arrayStr[7]);
        double index9 = Double.valueOf(arrayStr[9]);
        //100分
        if (arrayStr[1].equals("0")) {
            arrayStr[2] = "0%";
        } else {
            Double doubleValue = index1 / (index1 + index3 + index5 + index7 + index9) * 100;
            String value = doubleGeTowDecimal(doubleValue) + "%";
            arrayStr[2] = value;
        }
        //80分
        if (arrayStr[3].equals("0")) {
            arrayStr[4] = "0%";
        } else {
            Double doubleValue = index3 / (index1 + index3 + index5 + index7 + index9) * 100;
            String value = doubleGeTowDecimal(doubleValue) + "%";
            arrayStr[4] = value;
        }
        //60分
        if (arrayStr[5].equals("0")) {
            arrayStr[6] = "0%";
        } else {
            Double doubleValue = index5 / (index1 + index3 + index5 + index7 + index9) * 100;
            String value = doubleGeTowDecimal(doubleValue) + "%";
            arrayStr[6] = value;
        }
        //40分
        if (arrayStr[7].equals("0")) {
            arrayStr[8] = "0%";
        } else {
            Double doubleValue = index7 / (index1 + index3 + index5 + index7 + index9) * 100;
            String value = doubleGeTowDecimal(doubleValue) + "%";
            arrayStr[8] = value;
        }
        //20分
        if (arrayStr[9].equals("0")) {
            arrayStr[10] = "0%";
        } else {
            Double doubleValue = index9 / (index1 + index3 + index5 + index7 + index9) * 100;
            String value = doubleGeTowDecimal(doubleValue) + "%";
            arrayStr[10] = value;
        }
        return arrayStr;
    }

    //保留2位小数 并转成String
    private String doubleGeTowDecimal(Double doubleNum) {
        DecimalFormat format = new DecimalFormat("00.00");
        String doubleStr = format.format(doubleNum);
        return doubleStr;
    }

    //平均值保留2位小数 并转成String
    private String doubleGeTowDecimal_Average(Double doubleNum) {
        DecimalFormat format = new DecimalFormat("00.00");
        String doubleStr = format.format(doubleNum * 10);
        return doubleStr;
    }

    //计算平均值
    //[0~12] [题目名称:0,100分:1,百分比:2,80分:3,百分比:4,60分:5,百分比:6,40分:7,百分比:8,20分:9,百分比:10,平均分:11]
    private String[] countAverage(String[] arrayStr) {
        arrayStr = countValue(arrayStr);
        return arrayStr;
    }

    //计算平均值
    private String[] countValue(String[] arrayStr) {
        double index1 = Double.valueOf(arrayStr[1]);
        double index3 = Double.valueOf(arrayStr[3]);
        double index5 = Double.valueOf(arrayStr[5]);
        double index7 = Double.valueOf(arrayStr[7]);
        double index9 = Double.valueOf(arrayStr[9]);
        double countDouble = (index1 + index3 * 0.8 + index5 * 0.6 + index7 * 0.4 + index9 * 0.2) * 10;
        if (countDouble == 0) {
            arrayStr[11] = "0";
        } else {
            double countSum = index1 + index3 + index5 + index7 + index9;
            double divideValue = countDouble / countSum;
            String doubleStr = doubleGeTowDecimal_Average(divideValue);
            arrayStr[11] = doubleStr;
        }
        return arrayStr;
    }

    private String[] getStrArray(StationReport report, UserProfile userProfile) {
        String[] str = new String[14];
        str[0] = report.getCreationTimeStr();
        str[1] = userProfile.getRealName();
        str[2] = report.getStation().getProvince();
        str[3] = report.getStation().getName();
        str[4] = report.getStation().getCategory();
        str[5] = report.getStation().getBrand();
        str[6] = report.getStation().getStationNum();
        str[7] = getReportAnswer(report.getStation(), 184L);
        str[8] = getReportAnswer(report.getStation(), 185L);
        str[9] = getReportAnswer(report.getStation(), 13L);
        str[10] = getReportAnswer(report.getStation(), 182L);
        str[11] = getReportAnswer(report.getStation(), 14L);
        str[12] = getServiceReportAnswer(report, 155L);
        str[13] = getServiceReportAnswer(report, 157L);
        return str;
    }

    private String getReportAnswer(Station station, Long questionId) {
        StationReport stationReport = stationReportRepository.selectReport(station.getId());
        if (stationReport == null) {
            return "";
        }
        StationColorReport colorReport = stationColorReportRepository.selectReport(stationReport.getId(), questionId);
        if (colorReport == null) {
            return "";
        }
        if (StringUtils.isNotEmpty(colorReport.getAnswerOther())) {
            return colorReport.getAnswerOther();
        } else {
            String answerId = colorReport.getAnswerId();
            String[] ids = answerId.split(",");
            StringBuffer stringBuffer = new StringBuffer("");
            for (String id : ids) {
                QuestionAnswerOption answerOption = null;
                if (StringUtils.isNotEmpty(id)) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                }
                if (answerOption != null && answerOption.getName()!=null) {
                    if (StringUtils.isNotEmpty(answerOption.getName())) {
                        stringBuffer.append(answerOption.getName() + ",");
                    }
                }
            }
            return stringBuffer.toString();
        }
    }

    private String getServiceReportAnswer(StationReport stationReport, Long questionId) {
        StationRegularServiceReport serviceReport = stationRegularServiceReportRepository.selectQuestionOther(stationReport.getId(), questionId);
        if (serviceReport == null) {
            return "";
        }
        if (StringUtils.isNotEmpty(serviceReport.getAnswerOther())) {
            return serviceReport.getAnswerOther();
        } else {
            String answerId = serviceReport.getAnswerId();
            String[] ids = answerId.split(",");
            StringBuffer stringBuffer = new StringBuffer("");
            for (String id : ids) {
                QuestionAnswerOption answerOption = null;
                if (StringUtils.isNotEmpty(id)) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                }
                if (answerOption != null && answerOption.getName()!=null) {
                    if (StringUtils.isNotEmpty(answerOption.getName())) {
                        stringBuffer.append(answerOption.getName() + ",");
                    }
                }
            }
            return stringBuffer.toString();
        }
    }


}
